package com.epam.cdp.jpa.backingbeans;

import java.io.Serializable;
import java.util.ArrayList;
import java.util.List;

import javax.annotation.PostConstruct;
import javax.ejb.EJB;
import javax.faces.bean.ManagedBean;
import javax.faces.bean.SessionScoped;
import javax.faces.event.ValueChangeEvent;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;

import com.epam.cdp.jpa.dao.BookDAO;
import com.epam.cdp.jpa.model.Author;
import com.epam.cdp.jpa.model.Book;

@ManagedBean
@SessionScoped
public class BooksBackingBean implements Serializable {

    private static final long serialVersionUID = 1L;

    private final static Log log = LogFactory.getLog(BooksBackingBean.class);
    
    @EJB(beanName = "BookDAO", name = "BookDAO")
    private BookDAO bookDAO;
    
    private List<Author> selectedAuthors;
    
    private Book newBook = new Book();
    private Book selectedBook;
    
    @PostConstruct
    public void postConstruct() {
	log.info(" dao class is " + bookDAO.getClass());
    }

    public void authorListUpdated(ValueChangeEvent event) {
	
	log.debug("authorListUpdated: " + event.getNewValue());
    }
    
    public void addNewBook() {
	bookDAO.persist(newBook);
	newBook = new Book();
    }
    
    public List<Book> getAllBooks() {
	List<Book> books = bookDAO.getAll();
	return books;
    }

    public void updateSelectedBookInfo() {
	log.debug("updateSelectedBookInfo");
	if (selectedBook != null) {
	    selectedBook.setAuthors(selectedAuthors);
	    log.debug("updating " + selectedBook);
	    bookDAO.update(selectedBook);
	    selectedAuthors = null;
	}
    }
    
    public Book getNewBook() {
        return newBook;
    }

    public void setNewBook(Book newBook) {
        this.newBook = newBook;
    }

    public Book getSelectedBook() {
        return selectedBook;
    }

    public void setSelectedBook(Book selectedBook) {
        this.selectedBook = selectedBook;
        selectedAuthors = this.selectedBook.getAuthors();
        if (selectedAuthors == null) {
            log.debug("null selectedAutors");
            selectedAuthors = new ArrayList<Author>();
        }
        log.debug("book selected " + selectedBook);
    }

    public List<Author> getSelectedAuthors() {
        return selectedAuthors;
    }

    public void setSelectedAuthors(List<Author> selectedAuthors) {
        this.selectedAuthors = selectedAuthors;
    }

    public void removebook(Book book) {
	if (book != null) {
	    bookDAO.remove(book.getId());
	}
    }
}
